<?php
namespace app\modules\admin\controllers;

use app\modules\admin\models\Imgs;
use Yii;
use yii\web\BadRequestHttpException;

class UploadController extends \yii\web\Controller
{
    public function actionUpload ()
    {
        // 文章ID
        $id = Yii::$app->request->post('article_id');
        $p1 = $p2 = [];

        // 如果没有图或者id非真，返回空
        if (empty($_FILES['Article']['name']) || empty($_FILES['Article']['name']['img']) || !$id) {
            echo '{}';
            return;
        }
        // 循环多张图进行上传和上传后的处理
        $img_nums = count($_FILES['Article']['name']['img']);
        for ($i = 0; $i < $img_nums; $i++) {
            // 上传之后的图是可以进行删除操作的，我们为每一个记录成功的商品图指定删除操作的地址
            $url = \yii\helpers\Url::toRoute(['upload/delete']);
            $imageUrl = $this->getPath($_FILES['Article']['name']['img']);
            $res = move_uploaded_file($_FILES['Article']['tmp_name']['img'], $imageUrl);
            if (false === $res) {
                continue;
            }
            $model = new Imgs();
            $model->meta_key = Yii::$app->params['article']['head_img'];
            $model->meta_value = $id;
            $model->imgUrl = $imageUrl;
            $key = 0;
            if ($model->save(false)) {
                $key = $model->img_id;
            }

            // 这是一些额外的其他信息，如果你需要的话
            // $pathinfo = pathinfo($imageUrl);
            // $caption = $pathinfo['basename'];
            // $size = $_FILES['Banner']['size']['banner_url'][$i];


            $p1[$i] = '/'.$imageUrl;
            $p2[$i] = ['url' => $url, 'key' => $key];
        }

        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        // 返回上传成功后的商品图信息
        return [
            'initialPreview' => $p1,
            'initialPreviewConfig' => $p2,
            'append' => true,
        ];
    }

    /**
     * @return array
     * @throws \Exception
     * @throws \Throwable
     */

    public function actionDelete ()
    {
        if ($id = Yii::$app->request->post('key')) {
            Imgs::findOne($id)->delete();
        } else {
            throw new BadRequestHttpException('请求错误');
        }
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return ['success' => true];
    }

    private function getPath($name)
    {
        $extenced = pathinfo($name,PATHINFO_EXTENSION);
        $filename = $this->random(32) . '.' . $extenced;
        $imageUrl = 'uploads/image/' . date('Ymd') . '/' . $filename;
        $dir = 'uploads/image/' . date('Ymd');
        if (!file_exists($dir)){
            mkdir ($dir,0777,true);
        }
        if (file_exists($imageUrl)) {
            $this->getPath($name);
        } else {
            $fp=fopen($imageUrl,"w+");
            fclose($fp);
            return $imageUrl;
        }
    }

    private function random($length){
        $captchaSource = "0123456789abcdefghijklmnopqrstuvwxyz";

        $captchaResult = "yii_"; // 随机数返回值
        $captchaSentry = ""; // 随机数中间变量
        for($i=0;$i<$length;$i++){
            $n = rand(0, 35); #strlen($captchaSource));
            if($n >= 36){
                $n = 36 + ceil(($n-36)/3) * 3;
                $captchaResult .= substr($captchaSource, $n, 3);
            }else{
                $captchaResult .= substr($captchaSource, $n, 1);
            }
        }
        return $captchaResult;
    }

}